package controller;

import helpers.CookieHelper;
import helpers.SolrHelper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debug.RealEstateDebug;

import model.RealEstate;
import model.SearchParam;
import model.SearchResult;

public class Search extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		Cookie example = new CookieHelper("example", URLEncoder.encode("Hà Nội", "UTF-8"));
		response.addCookie(example);
		
		try {
			request.getRequestDispatcher("/pages/search.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String key = request.getParameter("key");
		
		SearchParam searchParam = new SearchParam();
		
		//Check empty
		if (!key.isEmpty()) searchParam.setKey(key);
		
		SearchResult sr = (SearchResult) SolrHelper.search(searchParam);
		
		response.getWriter().println("Total result: " + sr.getTotalResult());
		response.getWriter().println("Query time: " + sr.getQueryTime());
		response.getWriter().println("Key search: " + key);
		response.getWriter().println("-------------------------------------------------");
		
		ArrayList<RealEstate> realEstates = (ArrayList<RealEstate>) sr.getListRealEstate();
		if (realEstates.size() > 0) {
			for(int i = 0; i < realEstates.size(); i++) {
				RealEstateDebug.debugWeb(realEstates.get(i), response);
				response.getWriter().println("-------------------------------------------------");
				response.getWriter().println("");
				response.getWriter().println("");
			}
		}
	}
}
